﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web.Mvc;
using Api.Common;
using AppManager.Model;
using AutoMapper;
using Newtonsoft.Json;
using AppManager.DomainModel;
using AppManager.IBLL;

namespace AppManager.Background
{
    public class MenuController : BaseController
    {
        IMenuService menuService;
        public MenuController(IMenuService menuServ)
        {
            menuService = menuServ;
        }
        // GET: App
        public ActionResult Create()
        {
            ViewBag.TableTitle = "菜單添加";
            Th.PageHeaderCrumbs = new List<string> { "菜單添加", "Home", "菜單管理" };
            Th.PageHeaderMenus = new Dictionary<string, string> { { "菜單列表", Url.Action("List") } };
            return View("Edit");
        }

        public ActionResult Edit(int? id)
        {
            ViewBag.TableTitle = "菜單修改";
            Th.PageHeaderCrumbs = new List<string> { "菜單修改", "Home", "菜單管理" };
            Th.PageHeaderMenus = new Dictionary<string, string> { { "菜單列表", Url.Action("List") } };

            if (id == null) return RedirectToAction("List");
            var user = menuService.GetModel(s => s.Id == id.Value);
            if (user == null) return RedirectToAction("List");

            var model = Mapper.Map<Sys_MenuEidtModel>(user);
            return View(model);
        }

        /// <summary>
        ///     下拉框選擇父菜單
        ///     如果沒有則不顯示該下拉框
        /// </summary>
        /// <returns></returns>
        public ActionResult MenuSelect()
        {
            //js中利用$('select').val(3).trigger('change')来选中select

            var list = menuService.GetListNoTrack();
            list = GetRootMenus(list);

            var menus = Mapper.Map<List<MenuListModel>>(list);
            menus.Insert(0, new MenuListModel()
            {
                Text = "顶级菜单",
                Value = "0",
            });
            MenuSelectModel model = new MenuSelectModel()
            {
                Menus = menus,
            };

            return PartialView("_MenuSelect", model);
        }

        private static List<Sys_Menu> GetRootMenus(List<Sys_Menu> list)
        {
            foreach (var item in list)
            {
                item.Children = list.Where(s => s.ParentId == item.Id).OrderBy(s => s.Sort);
                foreach (var child in item.Children)
                {
                    child.Parent = item;
                }
            }
            //找出其中没有父级菜单的,并且不是root菜单的（parentid!=0）
            var noParentList = list.Where(s => s.Parent == null && s.ParentId != 0);
            list = list.Where(s => s.ParentId == 0).ToList();

            list.AddRange(noParentList);
            return list.OrderBy(s => s.Sort).ToList();
        }

        /// <summary>
        ///     只能修改菜單名和登錄Id
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Edit(Sys_MenuEidtModel model)
        {
            #region
            if (model.Id > 0)
            {
                ViewBag.TableTitle = "菜單修改";
                Th.PageHeaderCrumbs = new List<string> { "菜單修改", "Home", "菜單管理" };
            }
            else
            {
                ViewBag.TableTitle = "菜單添加";
                Th.PageHeaderCrumbs = new List<string> { "菜單添加", "Home", "菜單管理" };
            }

            Th.PageHeaderMenus = new Dictionary<string, string> { { "菜單列表", Url.Action("List") } };
            #endregion

            //移除這三個屬性的驗證
            ModelState.Remove("Id");

            if (!ModelState.IsValid)
            {
                AddErrorInfo();
                return View(model);
            }

            try
            {
                var id = menuService.AddOrUpdate(model);

                if (id > 0)
                {
                    return RedirectToAction("List");
                }
                AddErrorInfo("操作失敗");
            }
            catch (DbEntityValidationException ex)
            {
                AddDbValidateionError(ex);
            }
            catch (Exception ex)
            {
                AddErrorInfo(ex.Message);
            }
            return View(model);
        }

        /// <summary>
        /// 将所有的菜单以jstree的方式显示处理啊
        /// </summary>
        /// <param name="id">点击选中的菜单</param>
        /// <returns></returns>
        public ActionResult LeftMenu(int? id)
        {
            var list = menuService.GetListNoTrack();
            list = GetRootMenus(list);
            var menus = Mapper.Map<List<MenuListModel>>(list);
            menus.Insert(0, new MenuListModel()
            {
                Text = "所有菜单",
            });
            return PartialView("_LeftMenu", menus);
        }

        /// <summary>
        /// 传递parentid，然后显示该菜单的子菜单
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult List(int? parentId, string name)
        {
            if (parentId == null) parentId = 0;

            if (string.IsNullOrEmpty(name))
            {
                name = "所有菜單";
            }
            ViewBag.TableTitle = name + "---子菜单";

            Th.PageHeaderCrumbs = new List<string> { "菜單列表", "Home", "菜單管理" };
            Th.PageHeaderMenus = new Dictionary<string, string> { { "菜單添加", Url.Action("Create") }, { "菜單排序", Url.Action("Sort") } };

            var list = menuService.GetListNoTrack(s => s.ParentId == parentId);


            var columns = new List<string> { "菜單名", "菜單鏈接", "操作" };
            ViewBag.Columns = columns;

            return View(list);
        }

        public ActionResult Sort()
        {
            ViewBag.TableTitle = "菜单排序";

            Th.PageHeaderCrumbs = new List<string> { "菜單排序", "Home", "菜單管理" };
            Th.PageHeaderMenus = new Dictionary<string, string> { { "菜單添加", Url.Action("Create") }, { "菜單列表", Url.Action("List") } };

            var list = menuService.GetListNoTrack();
            list = GetRootMenus(list);

            var menus = Mapper.Map<List<MenuListModel>>(list);
            return View(menus);
        }

        [HttpPost]
        public ActionResult Sort(string result)
        {
            List<SortModel> list;
            try
            {
                list = JsonConvert.DeserializeObject<List<SortModel>>(result);
            }
            catch (Exception ex)
            {
                return ResponseJsonFail(new AjaxResult { msg = "操作失败," + ex.Message });
            }
            var ids = list.Select(s => s.id);
            var menuList = menuService.GetListNoTrack(s => ids.Contains(s.Id));
            foreach (var item in menuList)
            {
                var menu = list.FirstOrDefault(s => s.id == item.Id);
                if (menu != null)
                {
                    item.ParentId = menu.parentid;
                    item.Sort = menu.sort;
                }
            }
            try
            {
                menuService.UpdateList(menuList);

                return ResponseJsonSuccess(new AjaxResult { msg = "操作成功", url = Url.Action("List") });
            }
            catch (Exception ex)
            {
                return ResponseJsonFail(new AjaxResult { msg = "操作失败," + ex.Message });
            }
        }

        /// <summary>
        ///     多选删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Delete(params int[] ids)
        {
            //如果有的話就
            if (ids == null || ids.Count() == 0)
            {
                return Json(new AjaxResult { status = false, msg = "請選擇一項" });
            }

            menuService.DeleteList(s => ids.Contains(s.Id));
            return Json(new AjaxResult { msg = "操作成功", url = Url.Action("List") });
        }

        public ActionResult Delete(int? id)
        {
            //如果有的話就
            if (id == null)
            {
                return RedirectToAction("List");
            }

            menuService.Delete(s => s.Id == id.Value);
            return RedirectToAction("List");
        }

        /// <summary>
        /// 显示Sidebar menu
        /// </summary>
        /// <returns></returns>
        public ActionResult SibeBar()
        {
            var list = menuService.GetListNoTrack();
            list = GetRootMenus(list);

            var menus = Mapper.Map<List<SidebarMenu>>(list);
            return PartialView("_Sidebar", menus);
        }
    }
}